package com.rongke.biz.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.rongke.biz.service.MedicalRecordManager;
import com.rongke.enums.CancerTypeEnum;
import com.rongke.enums.MedicalRecordSubInfoEnum;
import com.rongke.model.Chemotherapy;
import com.rongke.model.ChemotherapyMedicine;
import com.rongke.model.InspectionRecord;
import com.rongke.model.MedicalRecords;
import com.rongke.model.OperationRecord;
import com.rongke.model.PathologyReport;
import com.rongke.model.Radiotherapy;
import com.rongke.model.ReportRecord;
import com.rongke.service.ChemotherapyMedicineService;
import com.rongke.service.ChemotherapyService;
import com.rongke.service.InspectionRecordService;
import com.rongke.service.MedicalRecordsService;
import com.rongke.service.OperationRecordService;
import com.rongke.service.PathologyReportService;
import com.rongke.service.RadiotherapyService;
import com.rongke.service.ReportRecordService;
import com.rongke.utils.StringUtil;

/**
 * 病历管理业务层实现类
 * 
 * @author Administrator
 *
 */
@Service
public class MedicalRecordManagerImpl implements MedicalRecordManager {

    @Autowired
    private InspectionRecordService     inspectionRecordService;

    @Autowired
    private ReportRecordService         reportRecordService;

    @Autowired
    private OperationRecordService      operationRecordService;

    @Autowired
    private PathologyReportService      pathologyReportService;

    @Autowired
    private ChemotherapyService         chemotherapyService;

    @Autowired
    private RadiotherapyService         radiotherapyService;

    @Autowired
    private ChemotherapyMedicineService chemotherapyMedicineService;

    @Autowired
    private MedicalRecordsService       medicalRecordsService;

    @Override
    public List<JSONObject> getDetailTimeline(long medicalRecordId) {
        List<JSONObject> totalRecordList = new ArrayList<JSONObject>();

        // 检查记录
        List<JSONObject> inspectionList = getInspectionInTimeline(medicalRecordId);
        if (CollectionUtils.isNotEmpty(inspectionList)) {
            totalRecordList.addAll(inspectionList);
        }

        // 医生诊断书
        List<JSONObject> reportList = getReportInTimeline(medicalRecordId);
        if (CollectionUtils.isNotEmpty(reportList)) {
            totalRecordList.addAll(reportList);
        }

        // 手术记录
        List<JSONObject> operationList = getOperationInTimeline(medicalRecordId);
        if (CollectionUtils.isNotEmpty(operationList)) {
            totalRecordList.addAll(operationList);
        }

        // 术后病理报告
        List<JSONObject> pathologyList = getPathologyInTimeline(medicalRecordId);
        if (CollectionUtils.isNotEmpty(pathologyList)) {
            totalRecordList.addAll(pathologyList);
        }

        // 化疗记录
        List<JSONObject> chemotherapyList = getChemotherapyInTimeline(medicalRecordId);
        if (CollectionUtils.isNotEmpty(chemotherapyList)) {
            totalRecordList.addAll(chemotherapyList);
        }

        // 放疗记录
        List<JSONObject> radiotherapyList = getRadiotherapyInTimeline(medicalRecordId);
        if (CollectionUtils.isNotEmpty(radiotherapyList)) {
            totalRecordList.addAll(radiotherapyList);
        }

        // 按照时间倒序排列
        Collections.sort(totalRecordList, new Comparator<JSONObject>() {

            @Override
            public int compare(JSONObject o1, JSONObject o2) {
                String date1 = o1.getString("timeline");
                String date2 = o2.getString("timeline");
                if (StringUtil.isEmpty(date2)) {
                    return 0;
                }

                return date2.compareTo(date1);
            }
        });
        return totalRecordList;
    }

    /**
     * 化疗记录
     * 
     * @param medicalRecordId
     * @return
     */
    private List<JSONObject> getRadiotherapyInTimeline(long medicalRecordId) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("medical_record_id", medicalRecordId);
        List<Radiotherapy> radiotherapyList = radiotherapyService.selectByMap(params);

        if (CollectionUtils.isEmpty(radiotherapyList)) {
            return null;
        }

        List<JSONObject> result = new ArrayList<JSONObject>();
        for (Radiotherapy radiotherapy : radiotherapyList) {
            JSONObject jsonObj = new JSONObject();
            jsonObj.put("id", radiotherapy.getId());
            jsonObj.put("infoType", MedicalRecordSubInfoEnum.RADIOTHERAPY_RECORD.getName());
            jsonObj.put("date", radiotherapy.getStartTime() + "~" + radiotherapy.getEndTime());
            jsonObj.put("desc",
                "放疗记录：剂量" + radiotherapy.getAmount() + "，次数" + radiotherapy.getTimes());
            jsonObj.put("picUrl", radiotherapy.getPicUrl());
            jsonObj.put("timeline", radiotherapy.getStartTime());
            result.add(jsonObj);
        }
        return result;
    }

    /**
     * 化疗记录
     * 
     * @param medicalRecordId
     * @return
     */
    private List<JSONObject> getChemotherapyInTimeline(long medicalRecordId) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("medical_record_id", medicalRecordId);
        List<Chemotherapy> chemotherapyList = chemotherapyService.selectByMap(params);

        if (CollectionUtils.isEmpty(chemotherapyList)) {
            return null;
        }

        List<JSONObject> result = new ArrayList<JSONObject>();
        for (Chemotherapy chemotherapy : chemotherapyList) {
            JSONObject jsonObj = new JSONObject();
            jsonObj.put("id", chemotherapy.getId());
            jsonObj.put("infoType", MedicalRecordSubInfoEnum.CHEMOTHERAPY_RECORD.getName());
            jsonObj.put("date", chemotherapy.getStartDate() + "~" + chemotherapy.getEndDate());

            // 拼装全部的药品信息
            Map<String, Object> medicineParams = new HashMap<String, Object>();
            medicineParams.put("chemotherapy_id", chemotherapy.getId());
            List<ChemotherapyMedicine> medicineList = chemotherapyMedicineService
                .selectByMap(medicineParams);
            StringBuilder sb = new StringBuilder("化疗记录：");
            if (CollectionUtils.isNotEmpty(medicineList)) {
                for (ChemotherapyMedicine medicine : medicineList) {
                    sb.append(medicine.getMedicineName()).append('/');
                    sb.append(medicine.getAmount()).append('/');
                    sb.append(medicine.getMedicineTypeName()).append("  ");
                }
            }
            jsonObj.put("desc", sb.toString());
            jsonObj.put("picUrl", chemotherapy.getPicUrl());
            jsonObj.put("timeline", chemotherapy.getStartDate());
            result.add(jsonObj);
        }
        return result;
    }

    /**
     * 术后病理报告
     * 
     * @param medicalRecordId
     * @return
     */
    private List<JSONObject> getPathologyInTimeline(long medicalRecordId) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("medical_record_id", medicalRecordId);
        List<PathologyReport> pathologyRecordList = pathologyReportService.selectByMap(params);

        if (CollectionUtils.isEmpty(pathologyRecordList)) {
            return null;
        }

        List<JSONObject> result = new ArrayList<JSONObject>();
        for (PathologyReport pathology : pathologyRecordList) {
            JSONObject jsonObj = new JSONObject();
            jsonObj.put("id", pathology.getId());
            jsonObj.put("infoType", MedicalRecordSubInfoEnum.PATHOLOGY_REPORT.getName());
            jsonObj.put("date", pathology.getDate());
            jsonObj.put("desc", "术后病理报告：");
            jsonObj.put("picUrl", pathology.getPicUrl());
            jsonObj.put("timeline", pathology.getDate());
            result.add(jsonObj);
        }
        return result;
    }

    /**
     * 手术记录
     * 
     * @param medicalRecordId
     * @return
     */
    private List<JSONObject> getOperationInTimeline(long medicalRecordId) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("medical_record_id", medicalRecordId);
        List<OperationRecord> operationRecordList = operationRecordService.selectByMap(params);

        if (CollectionUtils.isEmpty(operationRecordList)) {
            return null;
        }

        List<JSONObject> result = new ArrayList<JSONObject>();
        for (OperationRecord operation : operationRecordList) {
            JSONObject jsonObj = new JSONObject();
            jsonObj.put("id", operation.getId());
            jsonObj.put("infoType", MedicalRecordSubInfoEnum.OPERATION_RECORD.getName());
            jsonObj.put("date", operation.getDate());
            jsonObj.put("desc", "手术记录：" + operation.getOperationName());
            jsonObj.put("picUrl", operation.getPicUrl());
            jsonObj.put("timeline", operation.getDate());
            result.add(jsonObj);
        }
        return result;
    }

    /**
     * 医生诊断书
     * 
     * @param medicalRecordId
     * @return
     */
    private List<JSONObject> getReportInTimeline(long medicalRecordId) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("medical_record_id", medicalRecordId);
        List<ReportRecord> reportRecordList = reportRecordService.selectByMap(params);

        if (CollectionUtils.isEmpty(reportRecordList)) {
            return null;
        }

        List<JSONObject> result = new ArrayList<JSONObject>();
        for (ReportRecord report : reportRecordList) {
            JSONObject jsonObj = new JSONObject();
            jsonObj.put("id", report.getId());
            jsonObj.put("infoType", MedicalRecordSubInfoEnum.REPORT_RECORD.getName());
            jsonObj.put("date", report.getTreatmentDate());
            jsonObj.put("desc",
                "医生诊断书：" + (StringUtil.isEmpty(report.getTnmInfo()) ? "" : report.getTnmInfo()));
            jsonObj.put("picUrl", report.getPicUrl());
            jsonObj.put("timeline", report.getTreatmentDate());
            result.add(jsonObj);
        }
        return result;
    }

    /**
     * 检查记录
     * 
     * @param medicalRecordId
     * @return
     */
    private List<JSONObject> getInspectionInTimeline(long medicalRecordId) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("medical_record_id", medicalRecordId);
        List<InspectionRecord> inspectionRecordList = inspectionRecordService.selectByMap(params);

        if (CollectionUtils.isEmpty(inspectionRecordList)) {
            return null;
        }

        List<JSONObject> result = new ArrayList<JSONObject>();
        for (InspectionRecord inspection : inspectionRecordList) {
            JSONObject jsonObj = new JSONObject();
            jsonObj.put("id", inspection.getId());
            jsonObj.put("infoType", MedicalRecordSubInfoEnum.INSPECTION_RECORD.getName());
            jsonObj.put("date", inspection.getCheckDate());
            jsonObj.put("desc", "检查记录：" + inspection.getCheckTypeName());
            jsonObj.put("picUrl", inspection.getPicUrl());
            jsonObj.put("timeline", inspection.getCheckDate());
            result.add(jsonObj);
        }
        return result;
    }

    @Override
    public MedicalRecords selectOrAddMrByUserId(String userId) {
        if (StringUtil.isEmpty(userId)) {
            return null;
        }
        MedicalRecords mrInfo = medicalRecordsService.selectByUserId(userId);
        if (null != mrInfo) {
            return mrInfo;
        }

        //同步创建病历信息
        mrInfo = new MedicalRecords();

        mrInfo.setUserId(userId);
        mrInfo.setName("达摩");
        mrInfo.setIdCard("123456");
        mrInfo.setAddress("dota2");
        mrInfo.setSex("男");
        mrInfo.setAge(23);
        mrInfo.setHeight("170");
        mrInfo.setWeight("60");

        mrInfo.setCancerTypeId(CancerTypeEnum.CANCER_JIECHANGAI.getCancerTypeId());

        mrInfo.setStaging("T1N1M0");
        mrInfo.setTreatmentDate("2016-05-01");
        mrInfo.setTreatmentHospital("协和医院");
        mrInfo.setTreatmentDoctor("张三");
        medicalRecordsService.insert(mrInfo);
        return mrInfo;
    }

    @Override
    public MedicalRecords selectByUserId(String userId) {
        if (StringUtil.isEmpty(userId)) {
            return null;
        }
        return medicalRecordsService.selectByUserId(userId);
    }

}